package com.lipei.vrp.imp;

import java.util.ArrayList;

import org.apache.commons.lang3.StringUtils;

import com.lipei.vrp.AlgorithmType;
import com.lipei.vrp.IAlgorithm;
import com.lipei.vrp.Opt;
import com.lipei.vrp.ResultType;

public abstract class AbstractAlgorithm implements IAlgorithm {

	protected int m = -1;
	protected String[] args;
	protected AlgorithmType algtype = null;

	protected AbstractAlgorithm(String[] args) {
		this.args = args;
	}

	@Override
	public Opt parse(ArrayList<String> list, boolean timeout, boolean failed) {
		ResultType resulttype = null;
		if (timeout) {
			resulttype = ResultType.OT;
		}
		if (failed) {
			resulttype = ResultType.FAIL;
		}

		int i = list.size() - 1;
		for (; i >= 0; i--) {
			String line = list.get(i);
			if (line.contains("Total route length:")) {
				break;
			}
		}

		Opt opt;
		if (i >= 0) {
			ArrayList<String> sublines = new ArrayList<String>();
			int cost = i;
			i += 2;

			for (; i < list.size(); i++) {
				sublines.add(list.get(i));
			}
			opt = Opt.readroute2(sublines);
			String costline = list.get(cost);
			opt.cost = Double.parseDouble(StringUtils.trim(costline
					.substring(20)));
		} else {
			opt = new Opt();
			opt.resulttype = resulttype == null ? ResultType.NUL : resulttype;
		}

		opt.algtype = algtype;
		return opt;
	}

}
